import { Component } from '@angular/core';
import { ControlWidget } from '@delon/form';

@Component({
  selector: 'sl-noun',
  template: `
    <sf-item-wrap [id]="id" [schema]="schema" [ui]="ui" [showError]="showError" [error]="error" [showTitle]="schema.title">
      <nz-input-group nzCompact>
        <nz-input-number
          nzPlaceHolder="从"
          class="number-input"
          [nzMin]="ui.min || 0"
          [nzMax]="ui.max || 100000"
          [nzStep]="ui.step || 1"
          [ngModel]="min"
          (ngModelChange)="_change($event, 0)"
        ></nz-input-number>
        <input
          type="text"
          disabled
          nz-input
          placeholder="~"
          style="width: 30px; text-align: center; pointer-events: none; background-color: rgb(255, 255, 255);"
        />
        <nz-input-number
          nzPlaceHolder="到"
          class="number-input"
          [nzMin]="ui.min || 0"
          [nzMax]="ui.max || 100000"
          [nzStep]="ui.step || 1"
          [ngModel]="max"
          (ngModelChange)="_change($event, 1)"
        ></nz-input-number>
      </nz-input-group>
    </sf-item-wrap>
  `,
  preserveWhitespaces: false,
  styles: [
    `
      .number-input {
        width: calc(50% - 15px);
      }
    `,
  ],
})

// tslint:disable-next-line: component-class-suffix
export class NounWidget extends ControlWidget {
  static readonly KEY = 'noun';
  min!: number | null;
  max!: number | null;
  val: any[] = [];

  _change(value: any, index: number) {
    if (value.toString().trim() === '') {
      value = null;
    }
    if (index === 0) {
      this.min = value;
    }
    if (index === 1) {
      this.max = value;
    }

    this.val[index] = value;
    if (this.val.length === 2 && this.val[0] !== null && this.val[1] !== null) {
      this.setValue(this.val);
    } else {
      this.setValue(null);
    }
  }

  reset(value: string) {
    this.min = null;
    this.max = null;
  }
}
